"""
多线程编程

核心知识：
    1.操作系统最小调度单元为线程。
    2.对于IO操作来说，多线程和多进程性能差别不大。
"""

import time
import threading


def get_detail_html(url):
    print("get detail html started")
    time.sleep(2)
    print("get detail html end")


def get_detail_url(url):
    print("get detail url started")
    time.sleep(2)
    print("get detail url end")


def use_thread():
    t1 = threading.Thread(target=get_detail_html, args=("",))
    t2 = threading.Thread(target=get_detail_url, args=("",))

    start_time = time.time()

    t1.start()
    t2.start()

    # 线程阻塞
    t1.join()
    t2.join()

    print("耗时", time.time() - start_time)
    # 输出结果：
    """
    get detail html started
    get detail url started
    get detail html end
    get detail url end
    耗时 2.0020058155059814
    """


class GetDetailHtml(threading.Thread):
    """
    通过继承Thread类来实现多线程（复杂逻辑推荐使用）
    """

    def __init__(self, name):
        super().__init__(name=name)

    def run(self):
        print("get detail html started")
        time.sleep(2)
        print("get detail html end")


class GetDetailUrl(threading.Thread):
    def __init__(self, name):
        super().__init__(name=name)

    def run(self):
        print("get detail url started")
        time.sleep(2)
        print("get detail url end")


def use_thread_extend():
    t1 = GetDetailHtml(name="GetDetailHtml")
    t2 = GetDetailUrl(name="GetDetailUrl")

    start_time = time.time()

    t1.start()
    t2.start()

    # 线程阻塞
    t1.join()
    t2.join()

    print("耗时", time.time() - start_time)
    # 输出结果：
    """
    get detail html started
    get detail url started
    get detail url end
    get detail html end
    耗时 2.0044660568237305
    """


if __name__ == '__main__':
    # use_thread()
    use_thread_extend()
